package com.axxc.jpa.web;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.axxc.jpa.service.ISimpleCRUDService;
import com.axxc.jpa.vo.ResponseVO;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName: AbstractCurdController
 * @Description: 简单CRUDController
 * @author 熊小川
 * @date 2018年5月13日 下午2:53:50
 */
@RestController
public abstract class AbstractCurdController<M, F, ID extends Serializable> extends BaseController {

	@Autowired(required = false)
	protected ISimpleCRUDService<M, F, ID> service;

	@ApiOperation("按条件统计数量")
	@GetMapping("/count")
	public Long count(@ModelAttribute F filter) {
		Long count = this.service.count(filter);
		return count;
	}

	@ApiOperation("创建")
	@PostMapping("/create")
	public void create(@RequestBody M target) {
		this.service.insertIntoDB(target);
	}

	@ApiOperation("按条件分页查询")
	@GetMapping("/search")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "page", value = "当前页,此参数从0开始", paramType = "query"),
			@ApiImplicitParam(name = "size", value = "每页显示数量,此参数默认20", paramType = "query"),
			@ApiImplicitParam(name = "sort", value = "排序字段,可选多个,例如sort框中填        id,desc   ", dataType = "String", paramType = "query", allowMultiple = true, example = "sort=id desc") })
	public ResponseVO<List<M>> search(@ModelAttribute F filter, @ApiIgnore Pageable pageable) {
		logger.info("pageable :" + JSONObject.toJSONString(pageable));
		Page<M> page = this.service.search(filter, pageable);
		ResponseVO<List<M>> responseVO = new ResponseVO<>(page.getContent());
		if (page != null) {
			responseVO.setMessage("success");
			responseVO.setStatus(HttpStatus.OK);
			responseVO.setContent(page.getContent());
			responseVO.setTotal(page.getTotalElements());
			responseVO.setTotalPage(page.getTotalPages());
			responseVO.setCurrentPage(page.getNumber() + 1);
			responseVO.setPageSize(page.getSize());
		}
		return responseVO;
	}

}
